package com.kun.controller;

import java.util.Date;
import java.util.List;

import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.kun.entity.Book;
import com.kun.entity.Charity;
import com.kun.entity.Role;
import com.kun.entity.User;
import com.kun.result.ExceptionMsg;
import com.kun.result.Response;
import com.kun.result.ResponseData;
import com.kun.service.BookService;
import com.kun.service.CharityService;
import com.kun.service.RolePermissionService;
import com.kun.service.UserService;

/**
 * @description:
 * @author: KM
 * 2018年4月6日
 */

@Controller
@RequiresAuthentication
@RequestMapping("/admin")
public class AdminController extends BaseController{
	
	@Autowired
	private BookService  bookServiceImpl;
	
	@Autowired
	private UserService  userServiceImpl;
	
	@Autowired
	private CharityService charityService;
	
	@Autowired
	private RolePermissionService rolePermissionService;
	
	//共享图书  取回图书
	@RequiresPermissions("depositOrShare:operate")
	@RequestMapping(value="share",method=RequestMethod.POST) 
	@ResponseBody
    public Response share(@RequestParam(name = "userId") String userId,@RequestParam(name = "level") int level,
    		@RequestParam(name = "bookNumber") String bookNumber,@RequestParam(name = "amount") int amount,
    		@RequestParam(name = "state") String state,@RequestParam(name = "deposit") int deposit){
		Book book = bookServiceImpl.selectBookByBooknumber(bookNumber);
		if(book==null){
			return result(ExceptionMsg.BookNotExit);
		}
		User user1 = userServiceImpl.selectByPrimaryKey(userId);
		if(user1==null){
			return result(ExceptionMsg.LoginNameNotExists);
		}
		int isHave = 0;
		//判断用户当前是否存在押金会员的角色
		List<Role> roleList = rolePermissionService.selectRoleAndPermissionByUserId(userId);
		for (Role role : roleList) {
			if("love_vip".equals(role.getRoleName())){
				isHave = 1;
			}
		}
		if("1".equals(state)){//共享
			Charity charity = new Charity();
			charity.setCharityName("用户共享");
			charity.setUserId(userId);
			charity.setBookNumber(bookNumber);
			charity.setBookName(book.getBookname());
			charity.setAmount(amount);
			charity.setAddTime(new Date());
			charity.setState(state);
			charityService.insertCharity(charity);
			//加库存
			bookServiceImpl.updateAmountByBookNumber(bookNumber, amount,false);
			if(book.getBookowner().indexOf(user1.getRealname()) == -1){//图书共享者 不包含该名字，加上
				bookServiceImpl.updateAddBookOwnerByBooknumber(bookNumber, user1.getRealname());
			}
			if(isHave==0){
				//添加 爱心会员角色
				rolePermissionService.insertUserRole(userId, 5);
			}
		}else if("0".equals(state)){//取回
			List<Charity> lc = charityService.selectCharityByUserIdAndBooknumber(userId, bookNumber, "1");
			int count = 0;
			for(int i=0;i<lc.size();i++){
				Charity c = lc.get(i);
				count = count + c.getAmount();
			}
			if(count<amount){
				return new ResponseData(ExceptionMsg.AmountError,count);//数目不符
			}
			if(count==amount){
				if(book.getBookowner().indexOf(user1.getRealname()) != -1){//图书共享者 删除
					bookServiceImpl.updateDeleteBookOwnerByBooknumber(bookNumber, user1.getRealname());
				}
			}
			//减库存
			bookServiceImpl.updateAmountByBookNumber(bookNumber, -amount,false);
			for(int i=0;i<lc.size();i++){
				Charity c = lc.get(i);
				c.setBackTime(new Date());
				//慈善状态 数量更新
				if(c.getAmount()>amount){
					c.setAmount(c.getAmount() - amount);
					charityService.updateCharityByKey(c);
					break;
				}else if(c.getAmount()==amount){
					c.setState(state);
					charityService.updateCharityByKey(c);
					break;
				}else if(c.getAmount()<amount){
					c.setState(state);
					charityService.updateCharityByKey(c);
					amount = amount - c.getAmount();
					continue;
				}
			}
		}
		User user = new User();
		user.setId(userId);
		user.setLevel(level);
		if(level>0){
			user.setAuthProcess(3);
		}else if(deposit>0){
			user.setAuthProcess(2);
			if(isHave==1){
				rolePermissionService.deleteUserRole(user.getId(), 5);//移除爱心会员角色
			}
		}else{
			user.setAuthProcess(1);
			if(isHave==1){
				rolePermissionService.deleteUserRole(user.getId(), 5);
			}
		}
		userServiceImpl.updateUserByIdSelective(user);
		return result(ExceptionMsg.SUCCESS);
	}
	
}
